import $http from '@/utils/x-request';
import $tools from '@/utils/x-tools';
import $store from '@/store';
import $config from '@/config';

const Utils = {
  // 全局工具类
  $tools,
  // 全局request请求
  $http,
  /**
   * 获取当前页面路由
   * $getCurrentPage
   * **/
  $getCurrentPage() {
    try {
      const pages = getCurrentPages();
      return pages[pages.length - 1] || {};
    } catch (e) {
      return {};
    }
  },
  // 节流
  $throttle(fn, wait) {
    wait = wait || 200;
    let pre = +new Date();
    return function() {
      const context = this;
      const args = arguments;
      const now = +new Date();
      if (now - pre >= wait) {
        fn.apply(context, args);
        pre = +new Date();
      }
    };
  },
  /**
   * 选择文件
   * **/
  $choose(options) {
    return new Promise((resolve, reject) => {
      let opts;
      let choose;
      if (['image', 'video'].some(item => item === options.type)) {
        // 图片或者视频选择
        choose = uni.chooseMedia;
        opts = Object.assign({
          count: 9,
          maxDuration: 15, // 拍摄视频最长拍摄时间，单位秒。时间范围为 3s 至 30s 之间
          camera: 'back', // 仅在 sourceType 为 camera 时生效，使用前置或后置摄像头  back 使用后置摄像头 | front 使用前置摄像头
          mediaType: [options.type.toLowerCase()],
          sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  ['original', 'compressed']
          sourceType: ['album', 'camera'] // 从相册选择
        }, options);
      } else if (options.type === 'file') {
        // 从客户端会话选择文件
        choose = uni.chooseMessageFile;
        opts = Object.assign({
          count: 1,
          type: 'file',
          extension: ['pdf'] // 根据文件拓展名过滤
        }, options);
      } else {
        reject('缺少[type]值~');
      }
      // 开始文件选择
      choose({
        ...opts,
        success: (res) => {
          res.tempFiles.forEach(item => {
            item.type = opts.type || opts.mediaType[0];
          });
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        },
        complete: (e) => {
          // console.log('choose complete-> ', e)
        }
      });
    });
  },
  $getUserProfile() {
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (file) => {
        const userInfo = file.userInfo;
        uni.login({
          success: () => {
            $http({
              method: 'post',
              url: '/account/user/oauth',
              data: {
                userHeadImg: userInfo.avatarUrl,
                userNickname: userInfo.nickName,
                userProvince: userInfo.province,
                userCity: userInfo.city,
                userGender: userInfo.gender
              }
            }).then((res) => {
              $store.dispatch('user/updateUserInfo', res.data);
            });
          }
        });
      },
      fail: (err) => {
        console.log('getUserProfile fail-> ', err);
      }
    });
  },
  // 企业微信客服
  $openCustomerServiceChat(url, opts) {
    try {
      const params = Object.assign({
        extInfo: {
          url
        }
      }, opts);
      // 此事件必须是用户主动点击行为才能被触发
      wx.openCustomerServiceChat({
        ...params,
        fail: (err) => {
          console.log('openCustomerServiceChat fail-> ', err);
          if (['external', '99_mall'].includes($config.project) && err.errMsg !== 'openCustomerServiceChat:fail user cancel') {
            uni.showModal({
              content: '在线咨询功能维护中，请联系平台电话客服：4001005802',
              confirmText: '电话咨询',
              success: (res) => {
                if (res.confirm) {
                  uni.makePhoneCall({
                    phoneNumber: '4001005802'
                  });
                }
              }
            });
          }
          $store.dispatch('app/setAlarm', {
            code: 'openCustomerServiceChat',
            message: err.errMsg,
            url: 'wx.openCustomerServiceChat',
            requestData: params
          });
        }
      });
    } catch (e) {
      console.log('openCustomerServiceChat.catch->', e);
      uni.showToast({
        title: '请升级微信版本',
        icon: 'none'
      });
    }
  }
};
export default Utils;
